<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
         <el-form-item label="角色名称" prop="name">
            <el-input
               v-model="queryParams.name"
               placeholder="请输入角色名称"
               clearable
               style="width: 240px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="权限字符" prop="roleKey">
            <el-input
               v-model="queryParams.roleKey"
               placeholder="请输入权限字符"
               clearable
               style="width: 240px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
               v-hasPermi="['system:role:add']"
            >新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:role:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:role:remove']"
            >删除</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="角色编号" prop="id" width="120" />
         <el-table-column label="角色名称" prop="name" :show-overflow-tooltip="true" width="150" />
         <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="150" />
         <el-table-column label="描述" prop="description" :show-overflow-tooltip="true" width="200" />
         <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.id !== 1">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.id !== 1">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:role:remove']"></el-button>
              </el-tooltip>
            </template>
         </el-table-column>
      </el-table>

      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />

      <!-- 添加或修改角色配置对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
         <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="角色名称" prop="name">
               <el-input v-model="form.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item prop="roleKey">
               <template #label>
                  <span>
                     <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                        <el-icon><question-filled /></el-icon>
                     </el-tooltip>
                     权限字符
                  </span>
               </template>
               <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
            </el-form-item>
            <el-form-item label="描述">
               <el-input v-model="form.description" type="textarea" placeholder="请输入描述"></el-input>
            </el-form-item>
            <el-form-item label="菜单权限">
               <el-tree
                  ref="menuTreeRef"
                  :data="menuTree"
                  show-checkbox
                  node-key="id"
                  :default-checked-keys="checkedMenuIds"
                  :props="menuTreeProps"
                  style="width: 100%; max-height: 300px; overflow: auto;"
               />
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Role">
import { addRole, delRole, getRole, listRole, updateRole, getRoleMenu, updateRoleMenu } from "@/api/system/role";
import { getMenuTree } from "@/api/system/menu";

const router = useRouter();
const { proxy } = getCurrentInstance();

const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    roleKey: undefined
  },
  rules: {
    name: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

const menuTree = ref([]);
const checkedMenuIds = ref([]);
const menuTreeProps = { label: 'label', children: 'children' };

/** 查询角色列表 */
function getList() {
  loading.value = true;
  listRole(queryParams.value).then(response => {
    roleList.value = response.data;
    total.value = response.data.length;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?').then(function () {
    return delRole(roleIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加角色";
  getMenuTree().then(res => {
    menuTree.value = res.data;
    checkedMenuIds.value = [];
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const roleId = row.id || ids.value[0];
  getRole(roleId).then(response => {
    Object.assign(form.value, response.data);
    open.value = true;
    title.value = "修改角色";
    getMenuTree().then(res => {
      menuTree.value = res.data;
      getRoleMenu(roleId).then(res2 => {
        checkedMenuIds.value = res2.data;
      });
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      // 获取全选和半选节点，合并去重
      const checkedKeys = proxy.$refs.menuTreeRef.getCheckedKeys();
      const halfCheckedKeys = proxy.$refs.menuTreeRef.getHalfCheckedKeys();
      const allKeys = Array.from(new Set([...checkedKeys, ...halfCheckedKeys]));
      form.value.menuIds = allKeys;
      if (form.value.id != null) {
        updateRole(form.value).then(response => {
          updateRoleMenu({ roleId: form.value.id, menuIds: allKeys }).then(() => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
            getMenuTree().then(res => {
              menuTree.value = res.data;
              getRoleMenu(form.value.id).then(res2 => {
                checkedMenuIds.value = res2.data;
              });
            });
          });
        });
      } else {
        addRole(form.value).then(response => {
          updateRoleMenu({ roleId: response.data.id, menuIds: allKeys }).then(() => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
            getMenuTree().then(res => {
              menuTree.value = res.data;
              getRoleMenu(response.data.id).then(res2 => {
                checkedMenuIds.value = res2.data;
              });
            });
          });
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: null,
    name: null,
    roleKey: null,
    description: null
  };
  proxy.resetForm("roleRef");
}

getList();
</script>
